package com.easywan.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.easywan.dao.IBaseDao;
import com.easywan.dao.UsersMapper;
import com.easywan.service.UsersService;
import com.easywan.util.MD5Utils;
import com.easywan.util.Utils;
import com.easywan.vo.Users;

@Service
public class UsersServiceImpl extends BaseServiceImpl implements UsersService{
	@Autowired
	private UsersMapper usersMapper;
	@Override
	public List<Users> selectByName(String name) {
		return usersMapper.selectByName(name);
	}
	@Override
	public List<Users> selectByEmail(String email) {
		return usersMapper.selectByEmail(email);
	}
	/**
	 * 检查用户邮箱是否被注册
	 */
	@Override
	public boolean checkUsersEmail(String email) {
		return !Utils.listIsEmpty(usersMapper.selectByEmail(email));
	}
	/**
	 * 检查用户名是否被注册
	 */
	@Override
	public boolean checkUsersName(String name) {
		return !Utils.listIsEmpty(usersMapper.selectByName(name));
	}
	/**
	 * 添加用户
	 */
	@Override
	public void addUsers(Users users) {
		if(users.getEmail() == null){
			users.setEmail("");
		}
		if(users.getName() == null){
			users.setName("");
		}
		if(users.getPwd() == null){
			users.setPwd("");
		}
		if(users.getAge() == null){
			users.setAge(0);
		}
		if(users.getRealname() == null){
			users.setRealname("");
		}
		if(users.getEmailvif() == null){
			users.setEmailvif(false);
		}
		Date nowTime = new Date(System.currentTimeMillis());
		users.setCreatetime(nowTime);
		users.setModifytime(nowTime);
		usersMapper.add(users);
	}
	@Override
	public void vifCode(boolean i,String email) {
		Users users = new Users();
		users.setEmailvif(i);
		users.setEmail(email);
		usersMapper.updateVifCode(users);
	}
	@Override
	public void setPwd(Users users) {
		usersMapper.updatePwd(users);
	}
	@Override
	public Users login(Users users) {
		List<Users> userList = null;
		String name = users.getName();
		Boolean isEmail = Utils.isEmail(name);
		if(isEmail){
			userList = usersMapper.selectByEmail(name);
		}else{
			userList = usersMapper.selectByName(name);
		}
		if(Utils.listIsEmpty(userList)){
			return null;
		}else{
			if(users.getPwd() != null){
				if(MD5Utils.md5(users.getPwd()).equals(userList.get(0).getPwd())){
					return userList.get(0);
				}else{
					return null;
				}
			}else{
				return null;
			}
		}
	}
	@Override
	public IBaseDao getMapper() {
		// TODO Auto-generated method stub
		return this.usersMapper;
	}
}
